/*
 * @Author: FanWeiHua
 * @Date: 2021-05-14 17:31:19
 * @LastEditTime: 2021-07-23 17:11:01
 * @Description: node资源服务集合
 */
const path = require('path');
const fs = require('fs');
const { isFile } = require('../common/util');
/**
 * webpack的自定义配置
 */
const webpackConfig = JSON.parse(process.env.webpackConfig);
/**
 * 静态资源的服务
 */
exports.staticServer = [
  // 抽离出来的静态资源访问
  {
    url: '/excludeStatic/*',
    server: (req, res) => {
      const parsedUrl = decodeURI(req.url);
      const mkdirPathname = path.join(`${webpackConfig.project.path}`, `${parsedUrl}`); // 附件文件夹地址
      res.sendFile(mkdirPathname);
    }
  }
];
/**
 * 获取json文件内容
 * @param {*} mockPath mock文件夹路径
 * @param {*} callBack 返回的数据回调
 */
const getJsonContent = (mockPath, callBack) => {
  const file = fs.statSync(mockPath);
  if (file.isDirectory()) {
    /**
     * 解析mock的json文件
     */
    const analysisJson = folderPath => {
      const files = fs.readdirSync(folderPath);
      files.forEach(fileName => {
        // 获取文件扩展名，只对.json文件解析
        const extname = path.extname(fileName);
        if (extname === '.json') {
          const fillPath = folderPath + '/' + fileName;
          const file = fs.statSync(fillPath);
          // 如果是文件夹的话需要递归遍历下面的子文件
          if (file.isDirectory()) {
            analysisJson(fillPath);
          } else {
            const data = fs.readFileSync(fillPath, 'utf8');
            if (data) {
              const result = JSON.parse(data); // 读取的值
              if (typeof result === 'object' && result.servers instanceof Array) {
                callBack(result.servers);
              }
            }
          }
        }
      });
    };
    // 解析mock文件夹里的json文件
    analysisJson(mockPath);
  }
};
/**
 * 默认的mock服务
 */
exports.defaultMockServer = callBack => {
  const mockPath = path.resolve(__dirname, '../../mock');
  const state = isFile(mockPath);
  if (state) getJsonContent(mockPath, callBack);
};
/**
 * 每个项目mock服务
 */
exports.projectMockServer = callBack => {
  const projectMockPath = path.join(`${webpackConfig.project.path}`, '/mock');
  const state = isFile(projectMockPath);
  if (state) getJsonContent(projectMockPath, callBack);
};
